
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.net.*;
import java.sql.*;


public class Update_Thermostat extends HttpServlet{
	
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
	  int current_temp=-1;
	  int op_mode=-1;
	  int target_temp=-1;
	  int fan_mode=-1;
	  HttpSession session = request.getSession(true);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Enumeration paramNames = request.getParameterNames();
    while(paramNames.hasMoreElements()) {
      String paramName = (String)paramNames.nextElement();
	  String paramValue=request.getParameter(paramName);
	  String a="66";
	  System.out.println(paramValue+" "+paramName+Integer.parseInt(a));
		if(paramName.equals("current_temperature"))
		current_temp=Integer.parseInt(paramValue);
		else if(paramName.equals("op_mode"))
		op_mode=Integer.parseInt(paramValue);
		else if(paramName.equals("fan_op_mode"))
		fan_mode=Integer.parseInt(paramValue);
		else if(paramName.equals("target_temperature"))
		target_temp=Integer.parseInt(paramValue);
      }
	  
	String user="";
	Connection conn=null;
	Statement st=null;

	String url = "jdbc:oracle:thin:@localhost:1521";
	String dbName = ":orcl";
	String driver = "oracle.jdbc.driver.OracleDriver";
	String userName = "scott"; 
	String password = "tiger";
	
	try{
		Class.forName(driver).newInstance();
		}catch(Exception e){
		e.printStackTrace();
		}	
		try{
			conn = DriverManager.getConnection(url+dbName,userName,password);
			st=conn.createStatement();
		}catch(SQLException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if(session.getAttribute("username")!=null && session.getAttribute("username")!="")
		{
			System.out.println(current_temp+" "+op_mode+" "+fan_mode+" "+user);
			user = session.getAttribute("username").toString();
			String query="update  Thermostat_Current_Information set current_temperature="+current_temp+",operating_mode="+op_mode+",fan_operating_mode="+fan_mode+",target_temperature="+target_temp+" where username='"+user+"'";
			try{
			st.executeUpdate(query);}catch(Exception e){e.printStackTrace();}
			try{
			if(conn!=null)
			conn.close();
		}catch(SQLException e){
			e.printStackTrace();
		}
			response.sendRedirect("welcome.jsp");
		}
		
			
		}
 

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
